<template>
  <div>
    <a-modal v-model:open="open" title="梨信息" @ok="handleOk">
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">提交</a-button>
      </template>
      <!-- 表单内容 -->
      <a-form :model="loginUser" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="梨昵称">
          <a-input v-model:value="loginUser.userName" />
        </a-form-item>
        <a-form-item label="梨账号">
          <a-input v-model:value="loginUser.userAccount" />
        </a-form-item>
        <a-form-item label="梨简介">
          <a-textarea v-model:value="loginUser.userProfile" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { watch } from 'vue'
import { updateUserUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'

// 获取当前用户信息
const loginUser = ref()
const userStore = useLoginUserStore() // 获取状态管理实例

watch(
  () => userStore.loginUser,
  (newUserInfo) => {
    if (newUserInfo) {
      loginUser.value = { ...newUserInfo }
    }
  },
  { immediate: true }
)

// 修改信息表单布局配置
const labelCol = { style: { width: '150px' } }
const wrapperCol = { span: 14 }

const loading = ref<boolean>(false)
const open = ref<boolean>(false)

const childMethod = () => {
  open.value = true
}

const handleOk = async () => {
  loading.value = true
  try {
    const response = await updateUserUsingPost(loginUser.value)
    if (response.data.code === 0) {
      message.success('更新成功')
      userStore.setLoginUser({ ...loginUser.value })
      loading.value = false
      open.value = false
    } else {
      message.error('更新失败' + response.data.message)
    }
  } catch (error) {
    message.error('更新失败' + error)
  }
}

const handleCancel = () => {
  open.value = false
}

// 暴露方法，允许父组件访问
defineExpose({
  childMethod,
})
</script>
